<template>
  <div>
    <div style="margin:10px 5px; ">
      <el-input style="width:200px;margin-right: 5px;" suffix-icon="el-icon-search" v-model="name" placeholder="请输入名称"></el-input>
      <el-button type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>
    <div style="margin:20px 5px; ">
      <el-button type="primary" @click="handleAdd">新增&nbsp;<i class="el-icon-circle-plus-outline"></i></el-button>
      <el-button type="danger" @click="delbatch">批量删除&nbsp;<i class="el-icon-remove-outline"></i></el-button>
    </div>
    <el-table border :data="tableData" :header-cell-style="{background:'#eef1f6',color:'#606266'}" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="id" label="ID" align="center">
      </el-table-column>
      <el-table-column prop="name" label="名称" align="center">
      </el-table-column>
      <el-table-column prop="flag" label="唯一标识" align="center">
      </el-table-column>
      <el-table-column prop="description" label="描述" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="SelectMenu(scope.row)"><i class="el-icon-menu"></i>分配菜单</el-button>
          <el-button @click="handleEdit(scope.row)" type="success" size="mini"><i class="el-icon-edit"></i>编辑</el-button>
          <el-button @click="del(scope.row.id)" type="danger" size="mini"><i class="el-icon-delete"></i>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding-top: 20px;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum" :page-sizes="[10, 15, 20, 35]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" center width="30%">
      <el-form :rules="rules" ref="form" :model="form" size="small">
        <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="唯一标识" :label-width="formLabelWidth" prop="flag">
          <el-input v-model="form.flag" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth" prop="description">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clear">取 消</el-button>
        <el-button type="primary" @click="save('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="菜单分配" :visible.sync="menuDialogVis" width="30%">
      <el-tree :props="props" :data="menuData" show-checkbox node-key="id" ref="tree" :default-expanded-keys="expends" :default-checked-keys="checks">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span><i :class="data.icon"></i> {{ data.name }}</span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearmenu">取 消</el-button>
        <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

export default {
  name: 'Role',
  data () {
    return {
      props: {
        label: 'name',
      },
      //菜单分配
      menuData: [],
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      form: {
        name: '',
        description: '',
        flag: ''
      },
      input: "",
      name: "",
      email: "",
      address: "",
      dialogFormVisible: false,
      menuDialogVis: false,
      formLabelWidth: "80px",
      title: "角色信息",
      multipleSelection: [],
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        flag: [
          { required: true, message: "请输入唯一标识", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入描述", trigger: "blur" },
        ]
      },
      expends: [],
      checks: [],
      roleId: 0,
    };
  },
  created () {
    this.load();
  },
  methods: {
    //查询数据
    load () {
      this.request.get("/role/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name
        }
      }).then(res => {
        // 注意data
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    //新增
    save (form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.request.post("/role/save", this.form).then(res => {
            console.log(res);
            if (res.code = "200") {
              this.$message.success("保存成功")
              this.dialogFormVisible = false
              this.load()
            } else {
              this.$message.error("保存失败")
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //新增
    // save () {
    //   this.request.post("/role/save", this.form).then(res => {
    //     console.log(res);
    //     if (res.code = "200") {
    //       this.$message.success("保存成功")
    //       this.dialogFormVisible = false
    //       this.load()
    //     } else {
    //       this.$message.error("保存失败")
    //     }
    //   })
    // },
    saveRoleMenu () {
      // this.$refs.tree.getCheckedKeys() 获取菜单的keys 具体官网查看
      // console.log(this.$refs.tree.getCheckedKeys());
      // this.$refs.tree.getHalfCheckedKeys() 若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组 官网
      this.request.post('/role/roleMenu/' + this.roleId, this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())).then(res => {
        if (res.code === "200") {
          this.$message.success("绑定成功")
          this.menuDialogVis = false
          // 操作管理员角色后需要重新登录
          if (this.roleFlag === 'ROLE_ADMIN') {
            this.$store.commit("logout")
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    //编辑
    handleEdit (row) {
      this.form = row;
      this.dialogFormVisible = true;
      this.title = "编辑用户";
    },
    //删除
    del (id) {
      this.request.delete("/role/" + id).then(res => {
        this.$confirm("确认删除此用户嘛, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          if (res.code = "200") {
            this.$message.success("删除成功");
            this.load();
          }
          else {
            this.$message.error("删除失败");
          }
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
      });
    },

    //批量删除
    handleSelectionChange (val) {
      console.log(val);
      this.multipleSelection = val;
    },
    //点击批量删除的时候
    delbatch () {
      let ids = this.multipleSelection.map(r => r.id); // [{},{},{}]把对象数组变成纯ID数组 [1,2,3]
      if (ids.length == '') {
        return alert("请先选择需要删除的角色")
      }
      this.request.post("/role/del/batch", ids).then(res => {
        this.$confirm("你确定批量删除这些数据嘛, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          if (res.code = "200") {
            this.$message.success("批量删除成功");
            this.load();
          }
          else {
            this.$message.error("批量删除失败");
          }
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
      });
    },
    //点击之后打开弹窗
    handleAdd () {
      this.dialogFormVisible = true;
      //清空表单
      this.form = {};
    },
    handleSizeChange (val) {
      this.pageSize = val;
      this.load();
    },
    handleCurrentChange (val) {
      this.pageNum = val;
      this.load();
    },
    //重置
    reset () {
      this.name = "";
      this.load();
    },
    //点击取消
    clear () {
      this.load()
      this.dialogFormVisible = false
    },
    //点击取消
    clearmenu () {
      this.load()
      this.menuDialogVis = false
    },
    //请求菜单数据
    SelectMenu (role) {
      this.roleId = role.id
      this.roleFlag = role.flag
      this.request.get("/menu", {
        params: {
          name: ""
        }
      }).then(res => {
        // 注意data
        this.menuData = res.data
        this.expends = this.menuData.map(v => v.id) // 把后台返回的菜单数据处理成id数组
      })
      this.request.get("/role/roleMenu/" + this.roleId).then(res => {
        this.menuDialogVis = true
        this.checks = res.data
        this.request.get("/menu/ids").then(r => {
          const ids = r.data
          ids.forEach(id => {
            if (!this.checks.includes(id)) {
              this.$refs.tree.setChecked(id, false)
            }
          })

        })
      })

    },
  },
};
</script>

<style lang="less" scoped>
// div {

// }
</style>